using System;
using System.ComponentModel;
using NHibernate.Proxy.DynamicProxy;

namespace PurchaseSales.Manage.Common.AOP
{
    public class BaseInterceptor : IInterceptor
    {
        private PropertyChangedEventHandler changed = delegate { };

        public Object Proxy
        {
            get;
            set;
        }

        #region IInterceptor Members

        public Object Intercept(InvocationInfo info)
        {
            Boolean isSetter = info.TargetMethod.Name.StartsWith("set_") == true;
            Object result = null;

            if (info.TargetMethod.Name == "add_PropertyChanged")
            {
                PropertyChangedEventHandler propertyChangedEventHandler = info.Arguments[0] as PropertyChangedEventHandler;
                this.changed += propertyChangedEventHandler;
            }
            else if (info.TargetMethod.Name == "remove_PropertyChanged")
            {
                PropertyChangedEventHandler propertyChangedEventHandler = info.Arguments[0] as PropertyChangedEventHandler;
                this.changed -= propertyChangedEventHandler;
            }
            else
            {
                result = info.TargetMethod.Invoke(this.Proxy, info.Arguments);
            }

            if (isSetter == true)
            {
                String propertyName = info.TargetMethod.Name.Substring("set_".Length);
                this.changed(this.Proxy, new PropertyChangedEventArgs(propertyName));
            }

            return (result);
        }

        #endregion
    }
}